// app/middleware/security_middleware.js
'use strict';

const crypto = require('crypto');

module.exports = (options, app) => {
  return async function securityMiddleware(ctx, next) {
    // AC-SEC-001: 数据加密 - 敏感数据AES-256加密存储
    ctx.encryptSensitiveData = (data) => {
      const algorithm = 'aes-256-cbc';
      const key = crypto.scryptSync(app.config.security.encryptKey || 'default-key-32-chars-long!!', 'GfG', 32);
      const iv = Buffer.alloc(16, 0); // 初始化向量
      
      const cipher = crypto.createCipheriv(algorithm, key, iv);
      let encrypted = cipher.update(data, 'utf8', 'hex');
      encrypted += cipher.final('hex');
      return encrypted;
    };
    
    ctx.decryptSensitiveData = (encryptedData) => {
      const algorithm = 'aes-256-cbc';
      const key = crypto.scryptSync(app.config.security.encryptKey || 'default-key-32-chars-long!!', 'GfG', 32);
      const iv = Buffer.alloc(16, 0); // 初始化向量
      
      const decipher = crypto.createDecipheriv(algorithm, key, iv);
      let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
      decrypted += decipher.final('utf8');
      return decrypted;
    };
    
    // XSS防护 - 清理用户输入
    ctx.sanitizeInput = (input) => {
      if (typeof input === 'string') {
        return input
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;')
          .replace(/'/g, '&#x27;');
      }
      return input;
    };
    
    await next();
  };
};